package com.uziot.bucket.scope;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

/**
 * @author shidt
 * @version V1.0
 * @className ThreadLocalScope
 * @date 2020-12-19 16:59:58
 * @description 重新定义SCPOE注解，使用SCOPE注解
 * 可实现每次从容器中拿出对象时否是单例
 * 在WEB容器中，可定义：
 * 1、同一个请求多例
 * 2、同一个会话多例
 */


public class ThreadLocalScope implements Scope {

    private static final ThreadLocal<Object> THREAD_LOCAL_SCOPE = new ThreadLocal<>();

    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {
        Object value = THREAD_LOCAL_SCOPE.get();
        if (value != null) {
            return value;
        }

        Object object = objectFactory.getObject();
        THREAD_LOCAL_SCOPE.set(object);
        return object;
    }

    @Override
    public Object remove(String name) {
        THREAD_LOCAL_SCOPE.remove();
        return null;
    }

    @Override
    public void registerDestructionCallback(String name, Runnable callback) {

    }

    @Override
    public Object resolveContextualObject(String key) {
        return null;
    }

    @Override
    public String getConversationId() {
        return null;
    }
}